﻿using SharpDX;
using SharpDX.Direct3D11;
using System;

namespace Engine.Graphics
{
    internal class Shadowmap : Graphics.IRenderableObject
    {
        #region Public Fields

        public Matrix LightMatrix;

        public Matrix ProjectionMatrix;

        public Matrix ViewMatrix;

        #endregion Public Fields

        #region Private Fields

        private DepthStencilViewDescription depthBufferDesription;

        private DepthStencilView depthStencilView;

        private Engine engine;

        private Texture2DDescription zBufferTextureDescription;

        #endregion Private Fields

        #region Public Constructors

        public Shadowmap(Engine engine)
        {
            int bufferWidth = this.engine.Grafic.viewPort.Width;
            int bufferHeight = this.engine.Grafic.viewPort.Height;
            this.engine = engine;

            this.depthBufferDesription = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Flags = DepthStencilViewFlags.None,
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt
            };

            this.zBufferTextureDescription = new Texture2DDescription
            {
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = bufferWidth,
                Height = bufferHeight,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };

            CreateDepthStencilBuffer(bufferHeight, bufferWidth);
        }

        #endregion Public Constructors

        #region Public Properties

        public Texture2D rendertartget { get; set; }

        #endregion Public Properties

        #region Public Methods

        public void CreateDepthStencilBuffer(int height, int width)
        {
            if (this.depthStencilView != null)
            {
                this.depthStencilView.Dispose();
                this.depthStencilView = null;
            }

            var zBufferTexture = new Texture2D(engine.Grafic.Device, zBufferTextureDescription);
            this.depthStencilView = new DepthStencilView(engine.Grafic.Device, zBufferTexture);
            zBufferTexture.Dispose();
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Render(int renderStep)
        {
        }

        public void SetLightDirection(Vector3 direction)
        {
            // this.LightMatrix = Matrix.LookAtLH
        }

        #endregion Public Methods
    }
}